var editor;
var ArticleApp = function(){
	
	return{
		
		init:function(){
			ArticleApp.initForm();
			ArticleApp.initKindEditor();
			ArticleApp.loadGrid();
			ArticleApp.initType();
		},
		
		/**
		 * 加载富文本
		 */
		initKindEditor:function(){
			var webUrl = $("#APP_ROOT_PATH").val();
			var staticUrl = $("#STATIC_ROOT_PATH").val();
			editor = KindEditor.create('#content', {
				cssPath : staticUrl + 'gui/external/kindeditor/plugins/code/prettify.css',
				uploadJson : webUrl + 'file/edit_upload_pic?key=editor',
				allowImageUpload : true, 
				allowFileManager : false,
				items : [
							'undo','redo','fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
							'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
							'insertunorderedlist', '|', 'image','multiimage', 'link','source'],
				afterCreate : function() {
					
				}
			});
		},
		
		loadGrid:function(){
    		var url = $("#APP_ROOT_PATH").val() + 'article/page_data';
    		gui.widgets.BootStrap.loadGrid({
                gridSelector:"#grid-table",
                pagerSelector:"#grid-pager",
                postData:{
                	"title":function(){
                		return $.trim($("#title").val());
                	},
                	"categoryName":function(){
                		return $.trim($("#category").val());
                	}
                },
                jsonReader : {
                    root: "data.rows",
                    records: "data.total",
                    repeatitems : false,
                    total: function (obj) {
                        return  Math.ceil(obj.data.total /jQuery("#grid-table").getGridParam("rowNum"));
                    }
                } ,
                datatype: 'json',
                url:url,
                colNames:['话题','来源','阅读数','创建时间','操作'],
                colModel:[{name:'title'},
                          {name:'source'},
                          {name:'clickNum'},
                          {name:'gmtCreate'},
                          {name:'edit',sortable:false,formatter:function(cellvalue,options,rowObject){
                        	var html = "<div>"+
      						gui.widgets.BootStrap.colButton("icon-edit","编辑","ArticleApp.edit("+rowObject.id+")") + "</div>";
      						
      						html += gui.widgets.BootStrap.colButton("icon-remove","删除","ArticleApp.del("+rowObject.id+")")+"</div>";
      						
      						return html;
                          }}
                ],
                caption: "文库信息",
                rowList:[10,20,30],
                multiselect: true,
                prmNames:{
                    page:"pageNum",
                    rows:"pageSize",
                    sort: "sortField",
                    order: "sortOrder",
                    search:"_search"
                }
            });
    	},
    	/**
		 * 校验表单
		 */
		initForm:function(){
			jQuery.validator.addMethod("contentV", function(value, element) { 
				var len = editor.html().length;
				console.log(len)
				if(len > 20000){
					return false;
				}
				return true;
			}, "字数不能大于20000"); 
			
			jQuery.validator.addMethod("imgV", function(value, element) { 
				if(get_uploader_imgUrl()==null||get_uploader_imgUrl()==''){
					return false;
				}
				return true;
			}, "请上传至少一张图片！"); 
			
			$("#form").validate({
				ignore:[],
				rules: {
					title:{'required':true,'maxlength':30},
					category:{'required':true,},
					remark:{'maxlength':54},
					imgUrl:{'imgV':true}
				},
				messages:{
					title:{required:'标题不能为空',maxlength:'标题不能大于30个字'},
					category:{required:'分类不能为空'},
					remark:{required:'字数不能大于54个字'}
				},
				errorPlacement: function(error, element) {
					var placement = $(element).parents(".close-btn").find(".error_place")
					placement.html('');
                    error.appendTo(placement);
				},
				submitHandler:function(form){
					ArticleApp.save();
	            }
			});
		},
    	reload:function(){
    		jQuery("#grid-table").jqGrid('setGridParam',{page:1}).trigger("reloadGrid");
    	},
    
    	addPage:function(){
    		window.location.href= $("#APP_ROOT_PATH").val() + 'article/editor_page';
    	},
    	saveFrom:function(){
    		$("#form").submit();
    	},
    	/**
		 * 初始化分类类型
		 */
		initType:function(){
			var category=$("#hid_category").val();
			var url = $("#APP_ROOT_PATH").val() + 'article_catgory/load';
			gui.util.Ajax.asyncGET(url,null,function(res){
				var html = '<option value="">请选择类型</option>';
				$("#category").html('');
				for(var i=0;i<res.data.length;i++){
					var ss="";
					if(res.data[i].name==category){
						ss="selected='selected'"
					}
					html += '<option value="' + res.data[i].name + '" '+ ss +'>' + res.data[i].name + '</option>';
				}
				html+= '</option>';
				$("#category").html(html);
			});
		},
		bindEvent: function() {
			$("#category").change(function() {
				var category = $("#category").val(); //获取分类名
			})

		},
    	/**
    	 * 保存编辑
    	 */
    	save:function(){
    		editor.sync();//同步富文本中的内容
    		var title = $("#title").val();
			var categoryName =  $("#category").val();
			var author= $("#author").val();
			var source = $("#source").val();
			var remark= $("#remark").val();
			var cover = get_uploader_imgUrl();
			var content = KindEditor("#content").val();
			console.log("content:"+content.length)
			if(content.length > 20000){
				layer.msg('字数过多', {icon: 3});
				return false;
			}
			gui.util.Ajax.asyncPOST(
					 $("#APP_ROOT_PATH").val() + 'article/save',
        			{
		       				'title': title, 
		       				'categoryName': categoryName,
		       				'author':author,
		       				'source':source,
		       				'remark':remark,
		       				'cover':cover,
		       				'content':content
        			},
    				function(data){
        				if(data.ret != undefined && data.ret != 0){
           					layer.msg(data.message, {
       							icon: 1
       						});
           					return;
           				}
        				
        				if(data.data > 0){
        					layer.msg('保存成功', {
    							icon: 1
    						});
        					setTimeout(function(){
        						window.location.href=$("#APP_ROOT_PATH").val() + "article/index"
        					},1000)
        					//parent.location.reload();
        				}else{
        					layer.msg('保存失败', {
    							icon: 0
    						});
        				}
            		},
    				function(){
    				},
    				function(){
    				},
    				function(){
    					layer.closeAll();
    				}
    			)
    	},
    	/**
    	 * 取消
    	 */
    	calcel:function(){
    		window.location.href=$("#APP_ROOT_PATH").val() + 'article/index';
    	},
    	/**
    	 * 编辑
    	 */
    	edit:function(id){
    		window.location.href=$("#APP_ROOT_PATH").val() + 'article/editor?id='+id;
    	},
    	/**
    	 * 编辑更新
    	 */
    	updateEdit:function(id){
    		editor.sync();//同步富文本中的内容
    			var title = $("#title").val();
    			if(title.length > 60){
    				layer.msg('标题不能大于60个字', {icon: 3});
    				return;
    			}
    			
				var categoryName =  $("#category").val();
				if(categoryName.length > 30){
					layer.msg('标题不能大于60个字', {icon: 3});
    				return;
				}
				
				var author= $("#author").val();
				if(author.length > 15){
					layer.msg('作者长度不能大于15个字', {icon: 3});
    				return;
				}
				
				var source = $("#source").val();
				if(source.length > 15){
					layer.msg('作者长度不能大于15个字', {icon: 3});
    				return;
				}
				
				var remark= $("#remark").val();
				if(remark.length > 64){
					layer.msg('作者长度不能大于15个字', {icon: 3});
    				return;
				}
				var cover = get_uploader_imgUrl();
				var content = KindEditor("#content").val();
				
				if(content.length > 20000){
					layer.msg('字数过多', {icon: 3});
					return false;
				}
    		gui.util.Ajax.asyncPOST(
					 $("#APP_ROOT_PATH").val() + 'article/update',
       			{
					'id':id,	 
       				'title': title, 
       				'categoryName': categoryName,
       				'author':author,
       				'source':source,
       				'remark':remark,
       				'cover':cover,
       				'content':content
       			},
   				function(data){
       				if(data.ret != undefined && data.ret != 0){
       					layer.msg(data.message, {
   							icon: 1
   						});
       					return;
       				}
       				
       				if(data.data > 0){
       					layer.msg('更新成功', {
   							icon: 1
   						});
       					setTimeout(function(){
       						window.location.href=$("#APP_ROOT_PATH").val() + "article/index"
    					},1000)
       					//parent.location.reload();
       				}else{
       					layer.msg('更新失败', {
   							icon: 0
   						});
       				}
           		},
   				function(){
   				},
   				function(){
   				},
   				function(){
   					layer.closeAll();
   				}
   			)
    	},
    	del:function(id){
    		layer.confirm('您确定删除这条文章吗?', {icon: 3, title:'提示'}, function(index){
    			var url = $("#APP_ROOT_PATH").val() + '/article/del';
        		var params = {id:id};
        		gui.util.Ajax.asyncPOST(url,params,function(res){
        			if(res.ret != null && res.ret != ''){
        				layer.msg(res.message, {icon: 1});
        				return;
        			}
        			
        			layer.close(index);
        			if(res.data){
        				ArticleApp.reload();
        			}else{
        				layer.msg("删除失败", {icon: 1});
        			}
        		});
    			  
    		});
    		
    	}
	}
}();